import cv2
import numpy as np

# 读取图像和模板图像
image = cv2.imread('screenshot.png')
template = cv2.imread('template.png')

# 获取模板的宽高
w, h = template.shape[1], template.shape[0]

# 执行模板匹配
result = cv2.matchTemplate(image, template, cv2.TM_CCOEFF_NORMED)

# 设置匹配的阈值（可以调整）
threshold = 0.8
locations = np.where(result >= threshold)

# 统计出现次数，并绘制矩形框标记位置
count = len(locations[0])
for pt in zip(*locations[::-1]):  # locations[::-1]是将坐标反转成 (x, y)
    cv2.rectangle(image, pt, (pt[0] + w, pt[1] + h), (0, 255, 0), 2)

# 显示结果
cv2.imshow('Detected Objects', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

# 输出出现次数
print(f"模板出现次数: {count}")


